package org.lsy.service;

import lombok.extern.slf4j.Slf4j;
import org.lsy.model.Order;
import org.lsy.repository.OrderRepository;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * @author SHIYUAN
 * @version 1.0
 */
@Service
@Slf4j
public class OrderService {

    private final OrderRepository orderRepository;

    private final AmqpTemplate amqpTemplate;

    @Autowired
    OrderService(OrderRepository orderRepository, AmqpTemplate amqpTemplate) {
        this.orderRepository = orderRepository;
        this.amqpTemplate = amqpTemplate;
    }

    /**
     * 获取用户全部订单
     * @return 全部订单消息
     */
    public List<Order> findOrderList() {
        return orderRepository.findAll();
    }

    /**
     * 判断订单是否过期
     * @param id 订单号
     * @return 是否过期
     */
    public boolean isOutdated(String id) {
        Order order = orderRepository.findById(id).orElseThrow(() -> new RuntimeException("find order fails"));
        Integer status = order.getStatus();
        return status == 2;
    }

    /**
     * 生成订单
     * @return 订单号
     */
    public String createOrder() {
        String id = UUID.randomUUID().toString();
        Order order = new Order(id, 0);
        //订单入库
        orderRepository.save(order);
        //发送到消息队列
        amqpTemplate.convertAndSend("ex.order","order", id);
        return id;
    }

    /**
     * 支付订单
     * @param id 订单号
     */
    public void payForOrder(String id) {
        Order order = orderRepository.findById(id).orElseThrow(() -> new RuntimeException("find order fails"));
        Integer status = order.getStatus();
        //保证幂等性
        if (status == 0) {
            order.setStatus(1);
            orderRepository.save(order);
            log.info("支付订单");
        }
    }

    /**
     * 取消订单
     * @param id 订单号
     */
    public void cancelOrder(String id) {
        Order order = orderRepository.findById(id).orElseThrow(() -> new RuntimeException("find order fails"));
        Integer status = order.getStatus();
        //判断是否是支付成功的订单
        //保证幂等性
        if (status != 1) {
            order.setStatus(2);
        }
        orderRepository.save(order);
        log.info("订单过期");
    }
}
